<?php
session_start(); //we need to call PHP's session object to access it through CI
class ujian extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->data['menu'] = 'ujian';
		$this->data['form'] = 'custom/form_ujian';
		$this->data['title'] = 'Ujian';
		$admin = $this->session->userdata('admin');
		$params = array('tablename' => 'ujian', 'primary_key' => 'uj_id', 'where'=>array('ad_id'=>$admin['id']));
		$this->load->library('grid', $params);
	}

	function index()
	{
		$this->grid->add_subject('Ujian');
		$this->grid->add_field('uj_name', 'Nama Ujian', '', 'show');
		$this->grid->add_relation_field('mp_name', 'mata_pelajaran', 'mp_id', 'Mata Pelajaran', '', 'show');
		$this->grid->add_field("uj_date", 'Tanggal', '', 'show', true);
		$this->grid->add_field('uj_start', 'Mulai', '', 'show');
		$this->grid->add_field('uj_end', 'Selesai', '', 'show');
		$this->grid->add_field('uj_status', 'Status', '', 'show');
		$this->grid->set_menu('ujian');
		$this->grid->set_form('form_ujian');
		$this->grid->set_portlet_style('portlet box yellow');
		$this->grid->set_portlet_title('Data Ujian');
		$this->grid->show();
	}
	
	function upload($file_id, $folder="", $types="") {
	    if(!$_FILES[$file_id]['name']) return array('','No file specified');
	
	    $file_title = $_FILES[$file_id]['name'];
	    //Get file extension
	    $ext_arr = split("\.",basename($file_title));
	    $ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
	
	    //Not really uniqe - but for all practical reasons, it is
	    $uniqer = substr(md5(uniqid(rand(),1)),0,5);
	    $file_name = $uniqer . '_' . $file_title;//Get Unique Name
	
	    $all_types = explode(",",strtolower($types));
	    if($types) {
	        if(in_array($ext,$all_types));
	        else {
	            $result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
	            return array('',$result);
	        }
	    }
	
	    //Where the file must be uploaded to
	    if($folder) $folder .= '/';//Add a '/' at the end of the folder
	    $uploadfile = $folder . $file_name;
	
	    $result = '';
	    //Move the file from the stored location to the new location
	    if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
	        $result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
	        if(!file_exists($folder)) {
	            $result .= " : Folder don't exist.";
	        } elseif(!is_writable($folder)) {
	            $result .= " : Folder not writable.";
	        } elseif(!is_writable($uploadfile)) {
	            $result .= " : File not writable.";
	        }
	        $file_name = '';
	        
	    } else {
	        if(!$_FILES[$file_id]['size']) { //Check if the file is made
	            @unlink($uploadfile);//Delete the Empty file
	            $file_name = '';
	            $result = "Empty file found - please use a valid file."; //Show the error message
	        } else {
	            chmod($uploadfile,0777);//Make it universally writable.
	        }
	    }
	
	    return array($file_name,$result);
	}
	
	function upload_file(){
		list($name,$result) = upload('file','image_uploads','jpg,jpeg,gif,png');
		if($name) { // Upload Successful
			$details = stat("image_uploads/$name");
			$size = $details['size'] / 1024;
			print json_encode(array(
					"success"	=>	$result,
					"failure"	=>	false,
					"file_name"	=>	$name,	// Name of the file - JS should get this value
					"size"		=>	$size	// Size of the file - JS should get this as well.
			));
		} else { // Upload failed for some reason.
			print json_encode(array(
					"success"	=>	false,
					"failure"	=>	$result,
			));
		}
	}

	function form_value(){
		$admin = $this->session->userdata('admin');
		$value['uj_name'] = $this->input->post('uj_name');
		$value['mp_id'] = $this->input->post('mp_id');
		$value['uj_n_jawaban'] = $this->input->post('ans_tot');
		$value['ad_id'] = $admin['id'];
		$value['uj_date'] = date('Y-m-d', strtotime($this->input->post('uj_date')));
		$value['uj_start'] = date('H:i:s', strtotime($this->input->post('uj_start')));
		$value['uj_end'] = date('H:i:s', strtotime($this->input->post('uj_end')));
		return $value;
	}
	
	function init_data_form(){
		$this->data['uj_name'] = '';
		$this->data['mp_id'] = '';
		$this->data['uj_date'] = '';
		$this->data['uj_start'] = '';
		$this->data['uj_end'] = '';
		$this->data['uj_id'] = '';
		$this->data['uj_n_jawaban'] = '';
		$this->data['soals'] = array();
		$this->data['classes'] = array();
	}
	
	function drop_down_value(){
		$this->load->model('m_mata_pelajaran');
		$this->load->model('m_kelas');
		$this->data['row_mp'] = $this->m_mata_pelajaran->get_data();
		$this->data['kelas'] = $this->m_kelas->get_data();
	}

	function add(){
		$this->init_data_form();
		$this->drop_down_value();
		$this->data['act'] = 'insert';
		$this->data['portlet_style'] = 'portlet box blue';
		$this->data['portlet_title'] = 'Tambah Data Ujian';
		$this->data['action'] = base_url().'ujian/action/insert';
		$this->data['portlet_type'] = 'Form';
		$this->data['id'] = '';
		$this->load();
	}

	function action(){
		$this->load->model('m_ujian');
		$this->load->model('m_kelas_ujian');
		$act = $this->uri->segment(3);
		$value = $this->form_value();
		$id = $this->input->post('id');
		switch ($act){
			case "insert":
				$res = $this->m_ujian->insert($value);
				foreach($this->input->post('kelas') as $kelas){
					$data['uj_id'] = $res;
					$data['kl_id'] = $kelas;
					$this->m_kelas_ujian->insert($data);
				}
				break;
			case "update":
				if($this->m_ujian->update($value, array('uj_id' => $id))){
					$res = $id;
					$this->m_kelas_ujian->delete(array('uj_id' => $id));
					foreach($this->input->post('kelas') as $kelas){
						$data['uj_id'] = $res;
						$data['kl_id'] = $kelas;
						$this->m_kelas_ujian->insert($data, array('uj_id' => $id));
					}
				}
				break;
		}
		if($res){
			echo json_encode(array($res, "Proses berhasil"));
		}else{
			echo json_encode(array('0', "Proses gagal"));
		}
	}
	
	function get_external_value($id){
		$this->load->model('m_soal');
		$this->load->model('m_kelas_ujian');
		$this->data['soals'] = $this->m_soal->get_soal_by_ujian($id);
		$this->data['classes'] = array();
		foreach($this->m_kelas_ujian->get_kl_id($id) as $kls){
			$this->data['classes'][] = $kls['kl_id'];
		}
	}
	
	function is_expire($id){
		$this->load->model('m_ujian');
		$ujian = $this->m_ujian->get_data_by_id($id);
		if(strtotime($ujian['uj_date']." ".$ujian['uj_end']) < strtotime(date('d-m-Y H:i:s'))) return 1;
		else if((strtotime($ujian['uj_date']." ".$ujian['uj_start']) - strtotime(date('d-m-Y H:i:s'))) < 300) return 2;
		else return $ujian;
	}
	
	function update($id){
		$ujian = $this->is_expire($id);
		if($ujian==1){
			$this->grid->set_error('Ujian sudah berakhir, tidak dapat diubah');
			$this->index();
		}else if($ujian==2){
			$this->grid->set_error('Ujian akan / sedang berlangsung, tidak dapat diubah');
			$this->index();
		}else{
			$this->data = array_merge($this->data, $ujian);
			$this->data['act'] = 'update';
			$this->drop_down_value();
			$this->get_external_value($id);
			$this->data['portlet_style'] = 'portlet box red';
			$this->data['portlet_title'] = 'Update Data Siswa';
			$this->data['action'] = base_url().'siswa/action/update';
			$this->data['portlet_type'] = 'Form';
			$this->data['id'] = $id;
			$this->load();
		}
	}	
	
	function delete($id){
		$this->load->model('m_ujian');
		$res = $this->m_ujian->delete(array('uj_id' => $id));
		if($res!='1'){
			$this->data['error_message'] = 'Gagal';
		}
	}

	function aktivasi($id_ujian){
		$this->load->model("m_ujian");
		$res = $this->m_ujian->update(array('uj_status' => 1), array('uj_id' => $id_ujian));
		return $res;
	}
	
	function load(){
		if($this->session->userdata('admin')){
			$session_data = $this->session->userdata('admin');
			$this->data['username'] = $session_data['username'];
			$this->data['nama'] = $session_data['nama'];
			$this->load->view('main', $this->data);
		}else{
			redirect('admin', 'refresh');
		}
	}

}
?>